package cn.rulian.base.auth.service;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.rulian.base.auth.bo.User;
import cn.rulian.base.auth.dao.UserDao;
import cn.rulian.base.auth.vo.UserVo;
import cn.rulian.base.common.service.BaseService;
import cn.rulian.base.common.util.xx;
import cn.rulian.base.common.vo.Result;

/**
 * 用户管理Service
 */
@Service
@Transactional(readOnly = true)
public class UserService extends BaseService<User>
{
	// private final Logger log = LoggerFactory.getLogger(getClass());

	@Autowired
	EntityManager em;

	@Autowired
	private UserDao dao;

	@Override
	protected UserDao getDao()
	{
		return dao;
	}
		
	/**
	 * 查询
	 */
	public Result query(final UserVo vo)
	{
		Sort sort = new Sort("desc".equals(vo.getOrder())?Direction.DESC:Direction.ASC, vo.getSort()); // 排序
		Pageable pageable = new PageRequest(vo.getPage() - 1, vo.getRows(), sort); // 分页查询条件

		//动态查询对象
		Specification<User> specification = new Specification<User>()
		{
			@Override
			public Predicate toPredicate(Root<User> root, CriteriaQuery<?> cq, CriteriaBuilder cb)
			{
				return buildPredicate(root, cb, vo);
			}
		};

		// 查询
		Page<User> page = dao.findAll(specification, pageable);
		Result result = Result.getResult(page);

		return result;
	}
	

	/**
	 * 构建查询条件
	 */
	private Predicate buildPredicate(Root<User> root, CriteriaBuilder cb, UserVo vo)
	{
		List<Predicate> predicates = new ArrayList<Predicate>();


		//姓名
		String name = vo.getName();
		if(!xx.isEmpty(name))
		{
			predicates.add(cb.like(root.<String> get("name"), "%" + name + "%"));
		}


		//用户名
		String username = vo.getUsername();
		if(!xx.isEmpty(username))
		{
			predicates.add(cb.like(root.<String> get("username"), "%" + username + "%"));
		}
		

		//角色名
		String roleName = vo.getRoleName();
		if(!xx.isEmpty(roleName))
		{
			predicates.add(cb.like(root.<String> get("roleNames"), "%" + roleName + "%"));
		}
		
		
		// 机构ID
		Long organId = vo.getOrganId();
		if(organId != null)
		{
			long num = xx.toLong(organId);
			predicates.add(cb.equal(root.get("organ").get("id"), num));
		}

		// 机构名称
		String organName = vo.getOrganName();
		if(!xx.isEmpty(organName))
		{
			predicates.add(cb.like(root.get("organ").<String>get("name"), "%" + organName + "%"));
		}
		
		//排除特殊用户
		predicates.add(cb.notEqual(root.<String> get("username"), User.DEV));

		return cb.and(predicates.toArray(new Predicate[predicates.size()]));
	}

	
	/**
	 * 查询 Excel数据（不分页）
	 */
	public List<User> QueryExcelData(final UserVo vo)
	{
		Sort sort = new Sort("desc".equals(vo.getOrder())?Direction.DESC:Direction.ASC, vo.getSort()); // 排序
		//动态查询对象
		Specification<User> specification = new Specification<User>()
		{
			@Override
			public Predicate toPredicate(Root<User> root, CriteriaQuery<?> cq, CriteriaBuilder cb)
			{
				return buildPredicate(root, cb, vo);
			}
		};

		// 查询
		List<User> list = dao.findAll(specification, sort);
		return list;
	}

	/**
	 * 根据用户名和密码查找用户
	 */
	public User findUserByUserNameAndPwd(String userName,String pwd)
	{
		return dao.findFirstByUsernameAndPassword(userName, pwd);
	}
	

	/**
	 * 根据类型查询用户列表
	 */
	public List<User> findByType(String type)
	{
		return dao.findByTypeOrderByOrderNum(type);
	}

}
